package com.wang.gallerybackend.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.wang.gallerybackend.annotation.AuthCheck;
import com.wang.gallerybackend.common.AjaxResult;
import com.wang.gallerybackend.common.BaseResponse;
import com.wang.gallerybackend.exception.BusinessException;
import com.wang.gallerybackend.exception.ErrorCode;
import com.wang.gallerybackend.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
	@Resource
	private CosManager cosManager;

	/**
	 * 测试文件上传
	 * @return
	 */
	@AuthCheck(mustRole = "admin")
	@PostMapping("/test")
	public BaseResponse<String> upload(@RequestPart("file") MultipartFile multipartFile) {
		//指定文件目录
		String fileName = multipartFile.getOriginalFilename();
		String filePath = String.format("/test/%s", fileName);
		File file = null;
		try {
			file = File.createTempFile(filePath, null);
			multipartFile.transferTo(file);
			cosManager.putObject(filePath, file);
			return AjaxResult.success(filePath);
		} catch (IOException e) {
			throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
		} finally {
			if (file != null) {
				//删除临时文件
				boolean delete = file.delete();
				if(!delete){
					log.error("文件删除失败 = {}",filePath);
				}
			}
		}
	}
	/**
	 * 测试文件下载
	 */
	@AuthCheck(mustRole = "admin")
	@PostMapping("/download")
	public void textDownload(String filePath, HttpServletResponse response) throws IOException {
		COSObjectInputStream objectContent=null;
		try {
			COSObject object = cosManager.getObject(filePath);
			objectContent= object.getObjectContent();
			byte[] byteArray = IOUtils.toByteArray(objectContent);
			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
			//写入到响应中
			response.getOutputStream().write(byteArray);
			response.getOutputStream().flush();
		} catch (Exception e) {
			log.error("下载失败", e);
			throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
		}
		finally {
			//关闭流
			if(objectContent != null){
				objectContent.close();
			}
		}
	}


}
